<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>搜索框</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="/css/markdown.css">
    <link rel="stylesheet" href="/css/highlight.css">

</head>
<body>
<div>
    <!-- 封面图 -->
    <div class="banner" :style="articleCover">
        <div class="article-info-container">
            <!-- 文章标题 -->
            <div class="article-title">{{ article.articleTitle }}</div>
            <div class="article-info">
                <div class="first-line">
                    <!-- 发表时间 -->
                    <span>
              <i class="iconfont iconrili" />
              发表于 {{ article.createTime | date }}
            </span>
                    <span class="separator">|</span>
                    <!-- 发表时间 -->
                    <span>
              <i class="iconfont icongengxinshijian" />
              更新于
              <template v-if="article.updateTime">
                {{ article.updateTime | date }}
              </template>
              <template v-else>
                {{ article.createTime | date }}
              </template>
            </span>
                    <span class="separator">|</span>
                    <!-- 文章分类 -->
                    <span class="article-category">
              <i class="iconfont iconfenlei1" />
              <router-link :to="'/categories/' + article.categoryId">
                {{ article.categoryName }}
              </router-link>
            </span>
                </div>
                <div class="second-line">
                    <!-- 字数统计 -->
                    <span>
              <i class="iconfont iconzishu" />
              字数统计: {{ wordNum | num }}
            </span>
                    <span class="separator">|</span>
                    <!-- 阅读时长 -->
                    <span>
              <i class="iconfont iconshijian" />
              阅读时长: {{ readTime }}
            </span>
                </div>
                <div class="third-line">
                    <span class="separator">|</span>
                    <!-- 阅读量 -->
                    <span>
              <i class="iconfont iconliulan" /> 阅读量: {{ article.viewsCount }}
            </span>
                    <span class="separator">|</span>
                    <!-- 评论量 -->
                    <span>
              <i class="iconfont iconpinglunzu1" />评论数: {{ commentCount }}
            </span>
                </div>
            </div>
        </div>
    </div>
    <!-- 内容 -->
    <v-row class="article-container">
        <v-col md="9" cols="12">
            <v-card class="article-wrapper">
                <article
                        id="write"
                        class="article-content markdown-body"
                        v-html="article.articleContent"
                        ref="article"
                />

            </v-card>
        </v-col>
        <!-- 侧边功能 -->
        <v-col md="3" cols="12" class="d-md-block d-none">
            <div style="position: sticky;top: 20px;">
                <!-- 文章目录 -->
                <v-card class="right-container">
                    <div class="right-title">
                        <i class="iconfont iconhanbao" style="font-size:16.8px" />
                        <span style="margin-left:10px">目录</span>
                    </div>
                    <div id="toc" />
                </v-card>

            </div>
        </v-col>
    </v-row>
</div>

<script>
    new Vue({
        el: "#app",
        created() {
            this.getArticle();
        },
        destroyed() {
            this.clipboard.destroy();
            tocbot.destroy();
        },
        data: function() {
            return {
                config: {
                    sites: ["qzone", "wechat", "weibo", "qq"]
                },
                imgList: [],
                article: {
                    nextArticle: {
                        id: 0,
                        articleCover: ""
                    },
                    lastArticle: {
                        id: 0,
                        articleCover: ""
                    },
                    recommendArticleList: [],
                    newestArticleList: []
                },
                wordNum: "",
                readTime: "",
                commentType: 1,
                articleHref: window.location.href,
                clipboard: null,
                commentCount: 0
            };
        },
        methods: {
            getArticle() {
                const that = this;
                //查询文章
                this.axios.get("/articles/65").then(({ data }) => {
                    document.title = data.data.articleTitle;
                    //将markdown转换为Html
                    this.markdownToHtml(data.data);
                    this.$nextTick(() => {
                        // 统计文章字数
                        this.wordNum = this.deleteHTMLTag(this.article.articleContent).length;
                        // 计算阅读时间
                        this.readTime = Math.round(this.wordNum / 400) + "分钟";
                        // 添加代码复制功能
                        this.clipboard = new Clipboard(".copy-btn");
                        this.clipboard.on("success", () => {
                            this.$toast({ type: "success", message: "复制成功" });
                        });
                        // 添加文章生成目录功能
                        let nodes = this.$refs.article.children;
                        if (nodes.length) {
                            for (let i = 0; i < nodes.length; i++) {
                                let node = nodes[i];
                                let reg = /^H[1-4]{1}$/;
                                if (reg.exec(node.tagName)) {
                                    node.id = i;
                                }
                            }
                        }
                        tocbot.init({
                            tocSelector: "#toc", //要把目录添加元素位置，支持选择器
                            contentSelector: ".article-content", //获取html的元素
                            headingSelector: "h1, h2, h3", //要显示的id的目录
                            hasInnerContainers: true,
                            onClick: function(e) {
                                e.preventDefault();
                            }
                        });
                        // 添加图片预览功能
                        const imgList = this.$refs.article.getElementsByTagName("img");
                        for (var i = 0; i < imgList.length; i++) {
                            this.imgList.push(imgList[i].src);
                            imgList[i].addEventListener("click", function(e) {
                                that.previewImg(e.target.currentSrc);
                            });
                        }
                    });
                });
            },
            like() {
                // 判断登录
                if (!this.$store.state.userId) {
                    this.$store.state.loginFlag = true;
                    return false;
                };
            },
            markdownToHtml(article) {
                const MarkdownIt = require("markdown-it");
                const hljs = require("highlight.js");
                const md = new MarkdownIt({
                    html: true,
                    linkify: true,
                    typographer: true,
                    breaks: true,
                    highlight: function(str, lang) {
                        // 当前时间加随机数生成唯一的id标识
                        var d = new Date().getTime();
                        if (
                            window.performance &&
                            typeof window.performance.now === "function"
                        ) {
                            d += performance.now();
                        }
                        const codeIndex = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
                            /[xy]/g,
                            function(c) {
                                var r = (d + Math.random() * 16) % 16 | 0;
                                d = Math.floor(d / 16);
                                return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
                            }
                        );
                        // 复制功能主要使用的是 clipboard.js
                        let html = `<button class="copy-btn iconfont iconfuzhi" type="button" data-clipboard-action="copy" data-clipboard-target="#copy${codeIndex}"></button>`;
                        const linesLength = str.split(/\n/).length - 1;
                        // 生成行号
                        let linesNum = '<span aria-hidden="true" class="line-numbers-rows">';
                        for (let index = 0; index < linesLength; index++) {
                            linesNum = linesNum + "<span></span>";
                        }
                        linesNum += "</span>";
                        if (lang == null) {
                            lang = "java";
                        }
                        if (lang && hljs.getLanguage(lang)) {
                            // highlight.js 高亮代码
                            const preCode = hljs.highlight(lang, str, true).value;
                            html = html + preCode;
                            if (linesLength) {
                                html += '<b class="name">' + lang + "</b>";
                            }
                            // 将代码包裹在 textarea 中，由于防止textarea渲染出现问题，这里将 "<" 用 "<" 代替，不影响复制功能
                            return `<pre class="hljs"><code>${html}</code>${linesNum}</pre><textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy${codeIndex}">${str.replace(
                                /<\/textarea>/g,
                                "</textarea>"
                            )}</textarea>`;
                        }
                    }
                });
                // 将markdown替换为html标签
                article.articleContent = md.render(article.articleContent);
                this.article = article;
            },
            previewImg(img) {
                this.$imagePreview({
                    images: this.imgList,
                    index: this.imgList.indexOf(img)
                });
            },
            deleteHTMLTag(content) {
                return content
                    .replace(/<\/?[^>]*>/g, "")
                    .replace(/[|]*\n/, "")
                    .replace(/&npsp;/gi, "");
            },
            getCommentCount(count) {
                this.commentCount = count;
            }
        },
        computed: {
            blogInfo() {
                return this.$store.state.blogInfo;
            },
            articleCover() {
                return (
                    "background: url(" +
                    this.article.articleCover +
                    ") center center / cover no-repeat"
                );
            },
            isLike() {
                var articleLikeSet = this.$store.state.articleLikeSet;
                return articleLikeSet.indexOf(this.article.id) != -1
                    ? "like-btn-active"
                    : "like-btn";
            },
            isFull() {
                return function(id) {
                    return id ? "post full" : "post";
                };
            }
        }
    });
</script>
</body>
</html>
